﻿using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.ScheduleJob.SPI;

namespace T.FAS.Runtime.ScheduleJob.SubscriptionJobEngine
{
    public class NoticeImplProvider
    {
        public IScheduleJobSubscriptionNoticeHandler CreateNoticeHandler(ScheduleJobSubscriptionNoticeSet notice)
        {
            IScheduleJobSubscriptionNoticeHandler handler = null;
            var type = notice.SubscriptionNoticeDefinition.NoticeImplementation;
            if (string.IsNullOrEmpty(type))
                return null;
            handler = CreateInstance<IScheduleJobSubscriptionNoticeHandler>(type);
            return handler;
        }

        private static T CreateInstance<T>(string type)
        {
            object instance = null;
            try
            {
                instance = Activator.CreateInstance(Type.GetType(type));
                if (instance == null)
                {
                    throw new FasException(ScheduleJobRTPExceptionCode.ReflectNoticeImplException,
                        string.Format(ScheduleJobRTPExceptionCode.ReflectNoticeImplExceptionMessage, type));
                }
            }
            catch (Exception ex)
            {
                throw new FasException(ScheduleJobRTPExceptionCode.ReflectNoticeImplException,
                         string.Format(ScheduleJobRTPExceptionCode.ReflectNoticeImplExceptionMessage, type), ex);
            }

            return (T)instance;
        }
    }
}
